<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" :title="title" width="600px" @close="handleClose">
    <!--引用表格-->
    <BasicTable @register="registerTable">
      <!--操作栏-->
      <template #tableTitle>
        <a-button type="primary" color="success" @click="handleAdd"> 新增</a-button>
      </template>
      <template #action="{ record }">
        <TableAction :actions="getTableAction(record)" />
      </template>
    </BasicTable>
  </BasicDrawer>

  <!-- 表单区域 -->
  <ProductLevelModal @register="registerModal" :parentId="parentId" @success="handleSuccess"></ProductLevelModal>
</template>

<script lang="ts" name="product-productItem" setup>
  import { ref, computed, unref } from 'vue';
  import { useDesign } from '/@/hooks/web/useDesign';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { useModal } from '/@/components/Modal';
  import { useListPage } from '/@/hooks/system/useListPage';
  import { LevelColumns } from '../Product.data';
  import { levelList, levelDel } from '../Product.api';
  import ProductLevelModal from './ProductLevelModal.vue';

  const [registerModal, { openModal }] = useModal();
  const emit = defineEmits(['register', 'success']);
  const title = ref('');
  const parentId = ref('');

  //注册table数据
  const { tableContext } = useListPage({
    tableProps: {
      api: levelList,
      columns: LevelColumns,
      canResize: true,
      showIndexColumn: true,
      useSearchForm: false,
      showTableSetting: false,
      bordered: true,
      immediate: false,
      actionColumn: {
        width: 90,
      },
    },
  });

  const [registerTable, { reload, setProps }, { rowSelection, selectedRowKeys }] = tableContext;

  const [registerDrawer] = useDrawerInner(async (data) => {
    parentId.value = data.record.id;
    title.value = '客户等级 - ' + data.record.itemText 
    setProps({ searchInfo: { parentId: unref(parentId) } });
    reload();
  });

  /**
   * 新增事件
   */
  function handleAdd() {
    openModal(true, { isUpdate: false });
  }

  /**
   * 编辑事件
   */
  function handleEdit(record) {
    openModal(true, {
      record,
      isUpdate: true
    });
  }

  /**
   * 删除事件
   */
  async function handleDelete(record) {
    await levelDel({ id: record.id }, reload);
  }
  /**
   * 成功回调
   */
  function handleSuccess() {
    reload();
  }

  async function handleClose() {
    emit('success');
  }

  /**
   * 操作栏
   */
  function getTableAction(record) {
    return [
      {
        label: '编辑',
        onClick: handleEdit.bind(null, record),
      },
      {
        color: 'error',
        label: '删除',
        popConfirm: {
          title: '确定删除吗?',
          confirm: handleDelete.bind(null, record),
        },
      },
    ];
  }
</script>
<style scoped></style>
